package com.processor;

import com.advice.MyAdvice;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MockAopBeanPostPrc implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
        if (bean.getClass().getPackage().equals("impl.UserServiceImpl")) {
            Object beanProxy = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    new InvocationHandler() {
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            MyAdvice myAdvice = applicationContext.getBean(MyAdvice.class);
                            myAdvice.beforeAdvice();
                            Object result = method.invoke(bean, args);
                            myAdvice.afterAdvice();
                            return result;
                        }
                    }
            );

            return beanProxy;
        }
return null;
    }


        public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    }